package wt.jly.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import wt.jly.domain.User;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lanyangji
 * @date 2018/9/18 13:48
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final String IS_REMEMBER_ME = "1";

    /**
     * 用户登录
     *
     * @param user
     * @param rememberMe
     * @param request
     * @param model
     * @return
     */
    @PostMapping("/login")
    public String login(User user, String rememberMe, String code, HttpServletRequest request, Model model) {
        // 判断验证码是否正确
        if (!StringUtils.isEmpty(code)) {
            // 取出生成的验证码
            String verifyCode = (String)request.getSession().getAttribute("verifyCode");
            if (!code.equals(verifyCode)) {
                model.addAttribute("msg", "验证码输入有误！");
                return "login";
            }
        }


        // 使用shiro来进行登录验证
        Subject subject = SecurityUtils.getSubject();

        // AuthenticationToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());

        // shiro对密码进行加密
        Md5Hash hash = new Md5Hash(user.getPassword(), user.getUserName(), 2);
        // 开启rememberMe功能，要借助 AuthenticationToken 的子类 UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), hash.toString());
        // 开启 rememberMe 的功能
        if (!StringUtils.isEmpty(rememberMe) && IS_REMEMBER_ME.equals(rememberMe)) {
            token.setRememberMe(true);
        }

        try {
            subject.login(token);

            // 登录成功
            User dbUser = (User)subject.getPrincipal();
            request.getSession().setAttribute("user", dbUser);
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "该用户名不存在！");
            return "login";
        } catch (IncorrectCredentialsException e2) {
            model.addAttribute("msg", "密码错误！");
            return "login";
        }

        return "redirect:/index";
    }

    /**
     * 用户注销
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        // shiro底层删除session的会话信息
        subject.logout();

        return "redirect:/toLogin";
    }

}
